import React, { memo, useState, useEffect, useRef } from 'react';
import { Form } from 'antd';
import { connect } from 'umi';

import AutoRenderComponent from '@/pages/WorkFlow/components/FormControls/components/AutoRenderComponent/AutoRenderComponent';

const OrganizationNameItem = ({ form, formValueMap, organizationNameConfig, organizationCode, companySimpleList }) => {
    const [organizationName, setOrganizationName] = useState();
    const preOrganizationNameRef = useRef('');

    useEffect(() => {
        const orgName = organizationCode
            ? companySimpleList?.find(item => item.organizationCode === organizationCode)?.organizationName || null
            : null;

        setOrganizationName(orgName);
    }, [organizationCode, companySimpleList]);

    useEffect(() => {
        if (preOrganizationNameRef.current !== organizationName && organizationNameConfig?.formId) {
            preOrganizationNameRef.current = organizationName;
            form.setFieldsValue({ [organizationNameConfig.formId]: organizationName });
        }
    }, [form, organizationName, organizationNameConfig]);

    return (
        <>
            {organizationNameConfig != null ? (
                <Form.Item
                    label={organizationNameConfig.label}
                    key={organizationNameConfig.formId}
                    style={{ display: organizationNameConfig?.inRenderDom === false ? 'none' : 'block' }}
                >
                    {form.getFieldDecorator(organizationNameConfig?.formId, {
                        rules: organizationNameConfig?.rules,
                        value: formValueMap?.[organizationNameConfig.formId] ?? organizationName
                    })(<AutoRenderComponent form={form} config={organizationNameConfig} />)}
                </Form.Item>
            ) : null}
        </>
    );
};

const OrganizationNameItemConnect = memo(
    connect(({ finance }) => ({ companySimpleList: finance.companySimpleList }))(OrganizationNameItem)
);

export default OrganizationNameItemConnect;
